package com.menghao.rpc.consumer.handle.tcp;

import com.menghao.rpc.exception.InvokeException;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * <p>InvocationContext管理容器.<br>
 * <p>用于异步返回时，寻找InvocationContext以回写结果</p>
 *
 * @author MarvelCode.
 */
public class InvocationContextContainer {

    private ConcurrentMap<String, InvocationContext> requestContextMap = new ConcurrentHashMap<>();

    public void add(InvocationContext context) {
        String id = context.getRpcRequest().getId();
        InvocationContext old = requestContextMap.putIfAbsent(id, context);
        if (old != null) {
            throw new InvokeException("Duplicate InvocationContext conflict");
        }
    }

    public InvocationContext get(String id) {
        return requestContextMap.get(id);
    }

    public void remove(String id) {
        requestContextMap.remove(id);
    }
}
